import { ChangeDetectionStrategy, ChangeDetectorRef, Component } from '@angular/core';
import { _HttpClient, ModalHelper, SettingsService } from '@delon/theme';
import format from 'date-fns/format';
import { NzCascaderOption } from 'ng-zorro-antd/cascader';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class DashboardComponent {
  loading = true;
  isAdmin = false;
  q: {
    shopId: number;
  } = {
    shopId: 0
  };
  companyShopOptions: NzCascaderOption[] | null = [];
  values: any[] | null = null;

  statistics: any = {};
  today = new Date();

  preNotice = '';
  cNotice = '';

  formatPreOptionHelper(): void {
    if (this.today.getDay() <= 3) {
      this.preNotice = `上月3日至19日售后订单数量`;
    } else if (this.today.getDay() > 3 && this.today.getDay() <= 19) {
      this.preNotice = `本月3日至昨日售后订单数量`;
    } else {
      this.preNotice = `本月3日至18日售后订单数量`;
    }
  }

  formatCOptionHelper(): void {
    if (this.today.getDay() <= 3) {
      this.cNotice = `上月19日至昨日售后订单数量`;
    } else if (this.today.getDay() > 3 && this.today.getDay() <= 19) {
      this.cNotice = `上月19日至本月2日售后订单数量`;
    } else {
      this.cNotice = `本月19日至昨日售后订单数量`;
    }
  }

  constructor(
    private http: _HttpClient,
    private modal: ModalHelper,
    private msgSrv: NzMessageService,
    private cdr: ChangeDetectorRef,
    private settingService: SettingsService
  ) {
    //console.log(this.settingService.user.ID);
    if (this.settingService.user.ID == 1) {
      this.isAdmin = true;
    }
    this.http.get(`api/shop_map`).subscribe(res => {
      this.genCompanyShopOptions(res.data['companies'], res.data['shops']);
      // @ts-ignore
      this.q.shopId = this.values[1];
      this.loadDataFromServer(this.q);
      this.formatCOptionHelper();
      this.formatPreOptionHelper();
      this.cdr.detectChanges();
      this.loading = false;
    });
  }

  ngOnInit = (): void => {};

  genCompanyShopOptions(companies: any[], shops: any[]): void {
    let companyList: NzCascaderOption[] = [];
    companies.forEach((company: { ID: number; company_name: string }) => {
      let companyShopItem: NzCascaderOption = {
        value: company.ID,
        label: company.company_name,
        companyId: company.ID,
        isLeaf: false,
        children: [],
        disabled: true
      };
      companyList.push(companyShopItem);
    });
    companyList.forEach(company => {
      shops.forEach((shop: { shop_id: number; company_id: number; fordeal_shop_name: string }) => {
        if (shop.company_id == company.value) {
          let companyShopItem: NzCascaderOption = {
            value: shop.shop_id,
            label: shop.fordeal_shop_name,
            companyId: company.value,
            isLeaf: true,
            disabled: false
          };
          company.disabled = false;
          // @ts-ignore
          company.children.push(companyShopItem);
        }
      });
    });
    // @ts-ignore
    this.values = [companyList[0].value, companyList[0].children[0].value];
    this.companyShopOptions = companyList;
  }

  loadDataFromServer(params: any): void {
    this.loading = true;
    this.http.get(`api/statistics/shop`, params).subscribe(res => {
      if (res.err_code != 0) {
        this.msgSrv.error(res.msg);
        return;
      }
      this.statistics = res.data.shopStatistics;
      if (this.statistics['trans_at'] == '') {
        this.statistics['trans_at'] = '--';
      } else {
        this.statistics['trans_at'] = format(new Date(this.statistics['trans_at']), 'yyyy-MM-dd HH:mm:ss');
      }
      this.cdr.detectChanges();
      this.loading = false;
    });
  }

  formatPercent(v: number): string {
    v = v * 100;
    return `${v.toFixed(2)}%`;
  }

  onChanges(values: any) {
    this.q.shopId = values[1];
    this.loadDataFromServer(this.q);
  }
}
